import React, { Component } from 'react';
import {Button, Col, Form, Input, Popover, Row, Select} from 'antd';
import WrapFormItem from 'components/wrap-form-item';
import { messages } from 'share/common';
import Chooser from 'components/chooser';
import 'styles/setting/expense-type/expense-search-form.scss';
import Condition from 'components/condition';
import { setExpenseTypeSetOfBooks } from 'actions/setting';
import { connect } from 'react-redux';

import iconSwitchLeft from 'images/setting/expense-type/icon-switch-left.svg';

const { If, Else } = Condition;
const Option = Select.Option;

@connect(mapStateToProps)
@Form.create()
class ExpenseSearchForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      formList: [
        {
          dataIndex: 'setOfBooksId',
          component: WrapFormItem,
          params: {},
          child: (onChange, value) => (
            <Row>
              <Col span={6} className="expense-search-form-levelCode">
                <Condition>
                  <If value={props.tenant.tenantFormRecommend}>
                    <Select value={this.state.levelCode} onChange={this.handleChangeLevel}>
                      <Option key="TENANT">{messages('common-1.key424')/*租户*/}</Option>
                      <Option key="SET_OF_BOOK">{messages('common-1.key425')/*账套*/}</Option>
                    </Select>
                  </If>
                  <Else>
                    <div className="only-setOfBook">
                      <Popover content={messages('expense-6.key101')/*账套*/}>
                        {messages('expense-6.key101')/*账套*/}
                      </Popover>
                    </div>
                  </Else>
                </Condition>
              </Col>
              <Col span={12} className="expense-search-form-levelOrg">
                <Condition>
                  <If value={this.state.levelCode === 'TENANT'}>
                    <Popover content={this.props.tenant.tenantName} placement="topLeft">
                      <Input disabled value={this.props.tenant.tenantName}/>
                    </Popover>
                  </If>
                  <Else>
                    <Popover content={this.props.expenseTypeSetOfBooks.setOfBooksName} placement="topLeft">
                      <Select
                        listExtraParams={{ labelCategory: 1} }
                        onChange={innerValue => {
                          this.handleSetOfBooksChange(innerValue);
                        }}
                        value={value.setOfBooksId}
                        dropdownMatchSelectWidth={false}
                        dropdownStyle={{ maxWidth: 300 }}
                      >
                        {props.setOfBooks.map(item => <Option key={item.id}>{item.setOfBooksName}</Option>)}
                      </Select>
                    </Popover>
                  </Else>
                </Condition>
              </Col>
            </Row>
          )
        }, {
          dataIndex: 'expenseTypes',
          component: Chooser,
          params: {
            type: 'selectInvoiceType',
            valueKey: 'expenseTypeOID',
            labelKey: 'name',
            placeholder: messages('expense-6.key102')/*请选择费用类型*/,
            listExtraParams: {
            }
          },
          hide: true
        }, {
          dataIndex: 'companies',
          component: Chooser,
          params: {
            type: 'support_failure_company',
            labelKey: 'name',
            valueKey: 'companyOID',
            placeholder: messages('expense-6.key19')/*请选择启用公司*/,
            listExtraParams: {}
          },
          hide: true
        }],
      isHide: true,
      levelCode: this.props.expenseTypeSetOfBooks.expenseTypeLevelCode || "SET_OF_BOOK",
    };
  }


  handleSearch = () => {
    const { form: { validateFields }, setOfBooksChange } = this.props;
    validateFields((err, values) => {
      const params = {};
      const { expenseTypes, companies, setOfBooksId } = values;
      params.setOfBooksId = setOfBooksId.setOfBooksId;
      expenseTypes && (params.expenseTypeId = expenseTypes.map(item => item.id).join(','));
      companies && (params.companyId = companies.map(item => item.id).join(','));
      this.setState(values);
      setOfBooksChange(params)
    });
  };

  handleClear = () => {
    const { form: { resetFields }, id, setOfBooksChange } = this.props;
    this.setState({ expenseTypes: void 0, companies: void 0 });
    setOfBooksChange({ setOfBooksId: id });
    resetFields(['expenseTypes', 'companies']);
  };

  handleHide = () => {
    const { isHide, formList } = this.state;
    formList.map(item => {
      ['expenseTypes', 'companies'].includes(item.dataIndex) && (item.hide = !isHide);
      return item;
    });
    this.props.handleHide(!isHide);
    this.setState({ isHide: !isHide });
  };
  handlePutAway = () => {
    let putAway = !this.props.putAway;
    this.props.handlePutAway(putAway);
  };
  handleSetOfBooksChange = (value) => {
    const { setOfBooksChange, form: { resetFields, setFieldsValue } } = this.props;
    setOfBooksChange({ setOfBooksId: value })
      .then(() => {
        this.props.setOfBooks.map(item => {
          if(item.id === value)
            this.props.dispatch(setExpenseTypeSetOfBooks(Object.assign({}, item, { expenseTypeLevelCode: "SET_OF_BOOK" })));
        });
        setFieldsValue({ setOfBooksId: { setOfBooksId: value } });
        resetFields(['expenseTypes', 'companies']);
      })
  };

  handleChangeLevel = value => {
    const { expenseTypeSetOfBooks, form: { resetFields } } = this.props;
    this.props.setOfBooksChange({})
      .then(() => {
        this.setState({ levelCode: value });
        this.props.dispatch(setExpenseTypeSetOfBooks(Object.assign(
          {},
          expenseTypeSetOfBooks,
          { expenseTypeLevelCode: value })
        ));
        resetFields(['expenseTypes', 'companies']);
      })
  };

  render() {
    const { formList, isHide } = this.state;
    const { form: { getFieldDecorator }, setOfBooks, putAway, expenseTypeSetOfBooks,
      expenseTypeSetOfBooks: { expenseTypeLevelCode } } = this.props;
    const formItemLayout = { wrapperCol: { span: 24 } };
    return (
      <section className="expense-search-form">
        <section className="expense-search-form-header">
          {!putAway && (<div onClick={this.handleHide} className="more-wrap">
            {isHide ? messages('common.search')/*搜索*/ : messages('common.fold')/*收起*/}
          </div>)}
          <Popover content={putAway ? messages('expense-6.key103')/*展开*/ : messages('common.fold')/*收起*/}>
            <img src={iconSwitchLeft}
                 alt=""
                 className={putAway ? 'put-away icon-scale-status': 'icon-scale-status'}
                 onClick={this.handlePutAway}/>
          </Popover>
        </section>
        {!putAway && (<Form>
          {
            formList.map(item => {
              if (item.dataIndex === 'setOfBooksId') {
                item.params.setOfBooks = setOfBooks;
                item.initData = { setOfBooksId: this.props.expenseTypeSetOfBooks.id };
              }
              if (item.dataIndex === 'expenseTypes') {
                item.params.listExtraParams.setOfBooksId = expenseTypeLevelCode === 'TENANT' ? undefined : expenseTypeSetOfBooks.id;
                item.params.listExtraParams.levelCode = expenseTypeLevelCode;
                item.initData = this.state[item.dataIndex];
              }
              if (item.dataIndex === 'companies') {
                item.params.listExtraParams.setOfBooksId = expenseTypeLevelCode === 'TENANT' ? undefined : expenseTypeSetOfBooks.id;
                item.initData = this.state[item.dataIndex];
              }
              if (item.hide) return null;
              return (
                <Form.Item {...formItemLayout} extra={item.extra}>
                  {getFieldDecorator(item.dataIndex, {
                    rules: [{
                      required: !!item.required,
                      message: messages('common.select')/*请选择*/ + item.name
                    }],
                    initialValue: item.initData || void 0
                  })(React.createElement(item.component, item.params, item.child))}
                </Form.Item>
              );
            })
          }
        </Form>)}
        <If value={!isHide && !putAway}>
          <section className="expense-search-form-footer">
            <Button onClick={this.handleSearch} type="primary">{messages('common.search')/*搜索*/}</Button>
            <Button className="expense-search-form-clear" type="default" onClick={this.handleClear}>{messages('common.clear')/*清空*/}</Button>
          </section>
        </If>

      </section>
    );
  }
}

ExpenseSearchForm.propTypes = {};

function mapStateToProps(state) {
  return {
    tenant: state.login.tenant,
    expenseTypeSetOfBooks: state.setting.expenseTypeSetOfBooks
  }
}

export default ExpenseSearchForm;

